package com.study.project.service.impl;

import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.study.project.service.RedisCacheService;

/**
 * @program: studyProject
 * @description:
 * @author: yangjie
 * @create: 2024-04-13 14:28
 **/
@Service
public class RedisCacheServiceImpl implements RedisCacheService {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public String limitRate(String key, Integer time, TimeUnit timeUnit) {
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(key, key, time, timeUnit);
        if (Boolean.FALSE.equals(ifAbsent)) {
            throw new RuntimeException("限流了");
        }
        return null;
    }

    @Override
    public Object getCacheByKey(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    @Override
    public void setCacheByKey(String key, Object value) {
        redisTemplate.opsForValue().set(key, value, 1, TimeUnit.MINUTES);
    }
}